package com.example.financialsystem;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.financialsystem.adapter.BookAdapter;
import com.example.financialsystem.custom.AddBookDialog;
import com.example.financialsystem.fragment.BookDetailFragment;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import models.Book;
import models.Information;
import models.UserVO;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import others.ServerResponse;
import utils.OkHttpCallback;
import utils.OkhttpUtil;

import static others.Const.CURRENT_BOOK;
import static others.Const.CURRENT_USER;
import static others.Const.IP;
import static others.Const.PORT;
import static others.Const.SUCCESS;
import static others.Const.currentBook;
import static others.Tools.ToastShow;
import static utils.GsonUtil.Json2Class;
import static utils.GsonUtil.String2HashtableServerResponse;
import static utils.GsonUtil.String2ListBookServerResponse;
import static utils.GsonUtil.String2ListInfoServerResponse;

public class HomeScreenActivity extends AppCompatActivity {

    @BindView(R.id.accountBook)
    TextView ButtonBooks;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.accountChart)
    TextView ButtonChart;
    @BindView(R.id.drawer_username)
    TextView drawerUsername;
    @BindView(R.id.drawer_swipe_refresh)
    SwipeRefreshLayout drawerSwipeRefresh;
    @BindView(R.id.drawer_recyclerView)
    RecyclerView drawerRecyclerView;
    @BindView(R.id.drawer_add_book)
    TextView drawerAddBook;
    @BindView(R.id.homeAccount)
    TextView buttonHomeAccount;
    @BindView(R.id.homeFlow)
    TextView buttonHomeFlow;
    @BindView(R.id.homeAddRecord)
    TextView buttonHomeAddRecord;
    @BindView(R.id.homeInvest)
    TextView buttonHomeInvest;
    @BindView(R.id.homeSetting)
    TextView buttonHomeSetting;
    @BindView(R.id.homeFragment)
    FrameLayout homeFragment;
    @BindView(R.id.drawer_icon_image)
    CircleImageView drawerIconImage;

    public static final int FIRST_UPDATE_BOOK = 1;
    public static final int UPDATE_BOOK = 2;
    public static final int CHECK_INFORMATION = 3;
    public static final int RESPONSE_INVITE_INFORMATION = 4;

    @BindView(R.id.accountService)
    TextView accountService;

    private UserVO userVO;
    private List<Book> bookList = new ArrayList<>();

    private FragmentManager fragmentManager = getSupportFragmentManager();

    private AddBookDialog addBookDialog;

    private String userName;
    private String userId;

    private LocalBroadcastManager localBroadcastManager;
    private LocalReceiver localReceiver;
    private IntentFilter intentFilter;

    public String responseData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen);

        ButterKnife.bind(this);

        userVO = (UserVO) getIntent().getSerializableExtra(CURRENT_USER);
        userName = userVO.getUsername();
        userId = userVO.getId();

        drawerUsername.setText(userName);

        drawerSwipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        drawerSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.
                OnRefreshListener() {
            @Override
            public void onRefresh() {
                SearchBookByUser(userId, UPDATE_BOOK);
                drawerSwipeRefresh.setRefreshing(false);
            }
        });

        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        drawerRecyclerView.setLayoutManager(layoutManager);

        //加载用户账本数据
        SearchBookByUser(userId, FIRST_UPDATE_BOOK);

        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.financial.alreadyCreateNewBook");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);

        //检查消息
        checkInformation();

    }

    //各项菜单监听器
    @OnClick({R.id.accountBook, R.id.accountChart, R.id.drawer_add_book,
            R.id.homeAccount, R.id.homeFlow, R.id.homeAddRecord,
            R.id.homeInvest, R.id.homeSetting, R.id.accountService})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.accountBook:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.accountChart: {
//                ToastShow("该功能还没有开通，敬请期待");
                Intent intent = new Intent(this, ChartActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.drawer_add_book:
                ShowAddBookDialog(getWindow().getDecorView().findViewById(R.id.content));
                break;
            case R.id.homeAccount:
                break;
            case R.id.homeFlow: {
                Intent intent = new Intent(this, FlowActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.homeAddRecord: {
                Intent intent = new Intent(this, AddRecordActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.homeInvest:
                ToastShow("该功能还没有开通，敬请期待");
                break;
            case R.id.homeSetting:
                break;
            case R.id.accountService: {
                if (currentBook.getType() == 0){
                    ToastShow("该账本为个人账本");
                } else {
                    Intent intent = new Intent(this, BookManagementActivity.class);
                    startActivity(intent);
                }
                break;
            }
        }
    }

    //向服务器发起请求，查询用户所在账本
    public void SearchBookByUser(String userId, int updateType) {
        bookList.clear();
        String url = "http://" + IP + ":" + PORT + "/portal/book/searchByUserId.do";
        RequestBody requestBody = new FormBody.Builder()
                .add("userId", userId)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        SendRequest(request, updateType);
    }

    public void SendRequest(Request request, int updateType) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkhttpUtil.SendRequestWithPost(
                            request,
                            new OkHttpCallback() {
                                @Override
                                public void onFinish(String status, String responseData) {
                                    if (status.equals(SUCCESS)) {
                                        ServerResponse<List<Book>> serverResponse = String2ListBookServerResponse(responseData);
                                        bookList = serverResponse.getData();
                                        Message message = new Message();
                                        message.what = updateType;
                                        handler.sendMessage(message);
                                    } else {
                                        Looper.prepare();
                                        ToastShow("连接服务器失败,请稍后再试");
                                        Looper.loop();
                                    }
                                }
                            });
                } catch (Exception e) {
                    ToastShow("抱歉了亲,我们可能遇到了些麻烦");
                    e.printStackTrace();
                }
            }
        }).run();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case FIRST_UPDATE_BOOK:
                    UpdateBooks();
                    currentBook = bookList.get(0);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(CURRENT_BOOK, currentBook);
                    BookDetailFragment fragment = new BookDetailFragment();
                    fragment.setArguments(bundle);
                    ReplaceFragment(fragment);
                    break;
                case UPDATE_BOOK:
                    UpdateBooks();
                    ToastShow("更新成功");
                    break;
                case CHECK_INFORMATION: {
                    ServerResponse<List<Information>> serverResponse
                            = String2ListInfoServerResponse(responseData);
                    if (serverResponse.getStatus() == 0){
                        List<Information> information = serverResponse.getData();
                        for (int i=0;i<information.size();i++){
                            Information temp = information.get(i);
                            switch (temp.getType()){
                                case 0:
                                    dealInviteInformation(temp);
                                    break;
                                default:break;
                            }
                        }
                    } else {
                        ToastShow("检查消息出错2(HomeScreenActivity)");
                    }
                    break;
                }
                case RESPONSE_INVITE_INFORMATION:{
                    ServerResponse serverResponse = Json2Class(responseData);
                    if (serverResponse.getStatus() != 0){
                        ToastShow("响应操作出现了意外(HomeScreenActivity)");
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 更新账本信息RecyclerView
     */
    public void UpdateBooks() {
        BookAdapter adapter = new BookAdapter(bookList, mDrawerLayout,
                ButtonBooks, homeFragment, fragmentManager);
        drawerRecyclerView.setAdapter(adapter);
    }

    //更换碎片
    public void ReplaceFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.homeFragment, fragment);
        transaction.commit();
    }

    public void ShowAddBookDialog(View view) {
        addBookDialog = new AddBookDialog(this,
                R.style.MyDialog, localBroadcastManager);
        addBookDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        addBookDialog.setCanceledOnTouchOutside(true);
        addBookDialog.show();
    }

    class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            drawerSwipeRefresh.setRefreshing(true);
            SearchBookByUser(userId, UPDATE_BOOK);
            drawerSwipeRefresh.setRefreshing(false);
        }
    }

    public void checkInformation(){
        String url = "http://" + IP + ":" + PORT + "/portal/Information/CheckById.do";
        RequestBody requestBody = new FormBody.Builder()
                .add("recipientId", userId)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    responseData = response.body().string();
                    Message message = new Message();
                    message.what = CHECK_INFORMATION;
                    handler.sendMessage(message);
                } catch (Exception e){
                    e.printStackTrace();
                    ToastShow("检查消息出错1(HomeScreenActivity)");
                }
            }
        }).start();
    }

    public void dealInviteInformation(Information information){
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreenActivity.this);
        dialog.setTitle("好友邀请您加入新的账本");
        dialog.setMessage(information.getContext());
        dialog.setCancelable(false);
        dialog.setPositiveButton("同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                responseInformation(information.getInformationid(),0);
            }
        });
        dialog.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                responseInformation(information.getInformationid(),1);
            }
        });
        dialog.show();
    }

    public void responseInformation(String informationId,int option){
        String url = "http://" + IP + ":" + PORT + "/portal/Information/ResponseInformation.do";
        RequestBody requestBody = new FormBody.Builder()
                .add("informationId", informationId)
                .add("option",option+"")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    responseData = response.body().string();
                    Message message = new Message();
                    message.what = RESPONSE_INVITE_INFORMATION;
                    handler.sendMessage(message);
                } catch (Exception e){
                    e.printStackTrace();
                    ToastShow("相应消息出错1(HomeScreenActivity)");
                }
            }
        }).start();
    }
}
